package com.sc.nft.task;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.sc.nft.dao.*;
import com.sc.nft.entity.*;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.helper.LlPayHelper;
import com.sc.nft.helper.SandAccountHelper;
import com.sc.nft.service.CollectiveOrderService;
import com.sc.nft.service.CollectiveSalesService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Component
@RequiredArgsConstructor
@Slf4j
public class CollectiveTask {


    private final CollectiveSalesDao collectiveSalesDao;
    private final CollectiveSalesService collectiveSalesService;
    private final CollectiveOrderDao collectiveOrderDao;
    private final CollectiveOrderService collectiveOrderService ;
    private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    /**
     * 自动下架集售藏品
      */
    @XxlJob("autoCancel")
    public void autoCancel() throws Exception {
        List<CollectiveSales> onConsignListLimit = collectiveSalesDao.getAutoCloseListLimit(1000);
        onConsignListLimit.forEach(collectiveSalesService::autoCancel);
    }
    /**
     * 关闭超时订单
     *
     * @throws Exception
     */
    @XxlJob("autoCancelTimeOutOrder")
    public void closeTimeOutOrder() throws Exception {
        DateTime offset = DateTime.now().offset(DateField.SECOND, 30);//未来30秒
        List<CollectiveOrder> timeOutOrderIds = collectiveOrderDao.getPreTimeOutOrderIds(offset);
        timeOutOrderIds.forEach(collectiveOrder -> {
            try{
                long delayInSeconds = calculateDelayInSeconds(collectiveOrder.getCloseTime());
                executor.schedule(() -> collectiveOrderService.cancelOrderById(collectiveOrder.getId()), delayInSeconds, TimeUnit.SECONDS);
            }catch (Exception e){
                log.error("集售关闭订单失败:",e);
            }
        });
    }
    private long calculateDelayInSeconds(Date completeTime) {
        long currentTime = System.currentTimeMillis();
        long targetTime = completeTime.getTime();
        return (targetTime - currentTime) / 1000; // 转换为秒
    }
}
